﻿using System;
using System.Xml.Linq;

namespace Syno.Core.Xml
{
    public static class XElementHelper {
        public static string AsString(this XAttribute attribute)
        {
            return AsString(attribute, null);
        }

        public static int AsInt(this XAttribute attribute)
        {
            if (attribute == null)
            {
                return 0;
            }
            int value;
            if (int.TryParse(attribute.Value,out value))
            {
                return value;
            }
            return 0;
        }
        
        public static string AsString(this XAttribute attribute, string @default)
        {
            if (attribute == null)
            {
                return @default;
            }
            return attribute.Value;
        }


        public static string AsString(this XElement element)
        {
            return AsString(element, null);
        }

        public static string AsString(this XElement element, string @default)
        {
            if (element == null)
            {
                return @default;
            }
            return element.Value;
        }

        public static bool AsBoolean(this XAttribute attribute)
        {
            if (attribute == null)
            {
                return false;
            }
            bool value;
            if (Boolean.TryParse(attribute.Value,out value))
            {
                return value;
            }
            return false;
        }

        public static int AsInt(this XAttribute attribute, int i)
        {
            if (attribute == null)
            {
                return i;
            }
            return AsInt(attribute);
        }
    }
}